package com.clouddot.baipai.ui.fragment.H;

import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIPersonFragmentComponent;
import com.clouddot.baipai.contract.IPersonFragmentContract;
import com.clouddot.baipai.http.entity.response.getLeaveRecordResponse;
import com.clouddot.baipai.http.entity.response.getLeaveTypeResponse;
import com.clouddot.baipai.http.entity.response.getPersonInfoResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.module.PersonFragmentModule;
import com.clouddot.baipai.ui.activity.H_UMainActivity;
import com.clouddot.baipai.ui.adapter.LeaveRecordAdapter;
import com.clouddot.baipai.ui.adapter.leaveTypeAdapter;
import com.clouddot.baipai.util.SelectedBtnUtil;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.getTimeAndWeatherUtil;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;
import org.wxy.sdk.util.imageloader.ImageLoaderUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wxy on 2018/8/23.
 * 横版班牌个人的主页面
 */

public class H_PersonFrgment extends BaseFragment implements IPersonFragmentContract.IView {
    //存放请假类型的集合
    private List<getLeaveTypeResponse.LeaveTypeInfo> LeaveTypeInfolist = new ArrayList<>();
    //存放请假记录的集合
    private List<getLeaveRecordResponse.LeaveInfo> mDataList = new ArrayList<>();
    //请假类型的适配器
    private leaveTypeAdapter leaveTypeAdapter;

    private int currentPage = 1;
    private String selectIndex;
    private String selectIndexText;
    private Button[] buttons = new Button[2];
    private LeaveRecordAdapter adapter;
    private Animation loadingAnim;


    @Inject
    IPersonFragmentContract.IPresenter mPresenter;
    @BindView(R.id.image)
    ImageView imageView;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.uesrName)
    TextView uesrName;
    @BindView(R.id.className)
    TextView className;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.grade)
    TextView grade;
    @BindView(R.id.phoneNum)
    TextView phoneNum;
    @BindView(R.id.email)
    TextView email;
    @BindView(R.id.leave)
    Button leave;
    @BindView(R.id.leaveRecord)
    Button leaveRecord;
    @BindView(R.id.ed_leaveType)
    Spinner ed_leaveType;
    @BindView(R.id.ed_startTime)
    TextView ed_startTime;
    @BindView(R.id.ed_endTime)
    TextView ed_endTime;
    @BindView(R.id.ed_leaveReason)
    EditText ed_leaveReason;
    @BindView(R.id.apply)
    Button apply;
    @BindView(R.id.RecyclerView)
    RecyclerView recyclerView;

    @BindView(R.id.loading)
    ImageView loading;
    @BindView(R.id.loadingLP)
    RelativeLayout loadingLP;

    @BindView(R.id.content)
    ConstraintLayout content;
    @BindView(R.id.scanCard)
    ImageView scanCard;

    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.h_fragment_person, null);
    }

    @Override
    protected void initViews() {
        DaggerIPersonFragmentComponent.builder().personFragmentModule(new PersonFragmentModule(this)).build().inject(this);
        if (!Env.getAppContext().StudentID.isEmpty()) {
            content.setVisibility(View.VISIBLE);
            scanCard.setVisibility(View.GONE);
            mPresenter.getPersonInfo();
            mPresenter.getLeaveType("1");
        } else {
            content.setVisibility(View.GONE);
            scanCard.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initVariables() {

        loadingAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate);
        LinearInterpolator lir = new LinearInterpolator();
        loadingAnim.setInterpolator(lir);
        loading.startAnimation(loadingAnim);

        buttons[0] = leave;
        buttons[1] = leaveRecord;
        SelectedBtnUtil.selectedforText(buttons, buttons[0]);

        //初始化请假记录的配置
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addOnScrollListener(H_UMainActivity.listener);
    }

    @OnClick({R.id.leave, R.id.leaveRecord, R.id.apply, R.id.ed_startTime, R.id.ed_endTime})
    public void onClick(View view) {
        H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
        switch (view.getId()) {
            case R.id.leave:
                SelectedBtnUtil.selectedforText(buttons, buttons[0]);
                recyclerView.setVisibility(View.GONE);
                loadingLP.setVisibility(View.GONE);
                break;
            case R.id.leaveRecord:
                currentPage = 1;
                SelectedBtnUtil.selectedforText(buttons, buttons[1]);
                mPresenter.getLeaveRecord(currentPage, 10);
                loadingLP.setVisibility(View.VISIBLE);
                break;
            case R.id.apply:
                if (!checkLeaveContent()) {
                    mPresenter.applyLeave(selectIndex, selectIndexText, ed_startTime.getText().toString().trim(),
                            ed_endTime.getText().toString().trim(), ed_leaveReason.getText().toString().trim());
                }
                break;
            case R.id.ed_startTime:
                getTimeAndWeatherUtil.selectTime(getActivity().getSupportFragmentManager(), ed_startTime);
                break;
            case R.id.ed_endTime:
                getTimeAndWeatherUtil.selectTime(getActivity().getSupportFragmentManager(), ed_endTime);

                break;
        }
    }

    @Override
    protected void loadData() {
    }
    /**
     * fragment 隐藏和显现触发的方法，第一次生成的时候不会触发。
     *  hidden 为 false --> 显现 ；为 true --> 隐藏
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (!Env.getAppContext().StudentID.isEmpty()) {
                mPresenter.getPersonInfo();
                mPresenter.getLeaveType("1");
                content.setVisibility(View.VISIBLE);
                scanCard.setVisibility(View.GONE);
                leave.performClick();
            } else {
                content.setVisibility(View.GONE);
                scanCard.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     *
     * @param flag 1 --> 获取学生信息
     *             2 --> 进行请假
     *             3 --> 获取请假记录
     *             4 --> 获取请假类型
     * @param object
     */
    @Override
    public void success(int flag, Object object) {
        if (flag == 1) {
            refluesPersonInfo(object);
        } else if (flag == 2) {
            applyLeave();
        } else if (flag == 3) {
            refluesLeaveRecode(object);
        } else if (flag == 4) {
            getLeaveType(object);
        } else {
            ToastUtil.showToast(getActivity(), (String) object);
        }
    }

    @Override
    public void fail(int flag, String errMsg) {
        ToastUtil.showToast(getActivity(), errMsg);
    }


    /**
     *
     * 更新个人信息
     * @param object
     */
    private void refluesPersonInfo(Object object) {
        getPersonInfoResponse response = (getPersonInfoResponse) object;
        ImageLoaderUtil.getInstance().loadImage("http://" + Env.getAppContext().IP + response.Photo, imageView);
        name.setText(response.RealName + "(真实姓名)");
        uesrName.setText("用户名： " + (response.UserName.isEmpty() ? "未填写" : response.UserName));
        className.setText("班级： " + (response.ClassName.isEmpty() ? "未填写" : response.ClassName));
        sex.setText("性别： " + (response.Sex.isEmpty() ? "未填写" : response.Sex));
        grade.setText("年级： " + (response.GradeName.isEmpty() ? "未填写" : response.GradeName));
        phoneNum.setText("手机号码： " + (response.Mobile.isEmpty() ? "未填写" : response.Mobile));
        email.setText("邮箱： " + (response.Email.isEmpty() ? "未填写" : response.Email));
    }

    /**
     *
     * 更新请假记录
     * @param object
     */
    private void refluesLeaveRecode(Object object) {
        loadingLP.setVisibility(View.GONE);
        recyclerView.setVisibility(View.VISIBLE);
        getLeaveRecordResponse response = (getLeaveRecordResponse) object;
        if (response.EntityList.isEmpty()) {
            if (adapter != null) adapter.loadMoreEnd();
            return;
        }
        if (currentPage == 1) {
            mDataList = response.EntityList;
            adapter = new LeaveRecordAdapter(mDataList);
            adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    mPresenter.getLeaveRecord(++currentPage, 10);
                }
            });
            recyclerView.setAdapter(adapter);
        } else {
            adapter.addData(response.EntityList);
            adapter.loadMoreComplete();
        }
    }

    /**
     *
     * 更新请假类型数据
     * @param object
     */
    private void getLeaveType(Object object) {
        getLeaveTypeResponse response = (getLeaveTypeResponse) object;
        leaveTypeAdapter = new leaveTypeAdapter(getActivity());
        LeaveTypeInfolist = response.LeaveTypeList;
        leaveTypeAdapter.setDatas(LeaveTypeInfolist);
        selectIndex = response.LeaveTypeList.get(0).DimKey;
        selectIndexText = response.LeaveTypeList.get(0).DimValue;
        ed_leaveType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectIndex = LeaveTypeInfolist.get(position).DimKey;
                selectIndexText = LeaveTypeInfolist.get(position).DimValue;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        ed_leaveType.setAdapter(leaveTypeAdapter);
    }

    /**
     * 进行请假
     */
    private void applyLeave() {
        mPresenter.pushLeaveNo(Env.getAppContext().cardID, selectIndexText, ed_startTime.getText().toString().trim(),
                ed_endTime.getText().toString().trim(), ed_leaveReason.getText().toString().trim());
        ed_startTime.setText("");
        ed_endTime.setText("");
        ed_leaveReason.setText("");
        ed_leaveType.setSelection(0);
        ToastUtil.showToast(getActivity(), "请假成功");
    }


    /**
     * 检查请假内容不能为空
     * @return
     */
    private boolean checkLeaveContent() {
        if (!TextUtils.isEmpty(ed_startTime.getText().toString())
                && !TextUtils.isEmpty(ed_endTime.getText().toString())
                && !TextUtils.isEmpty(ed_leaveReason.getText().toString())) {
            return false;
        } else {
            ToastUtil.showToast(getActivity(), "内容不能为空");
            return true;
        }
    }


}
